package com.wlz.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

/**
 * 腾讯云对象存储操作工具类
 *
 * @author ：Administrator
 * @date ：2019/1/11/011 13:05
 */


public class CosUtils {

    private static Logger logger = LoggerFactory.getLogger(CosUtils.class);
    /**
     * 将输入流转换成图片，再上传到cos中
     *
     * @param is          输入流
     * @param openId      用户的openId
     * @param secretid    cos的secretid
     * @param secretkey   cos的secretkey
     * @param wxaCodePath 微信小程序码保存在COS上的地址
     * @return 返回图片保存地址
     */
    public static String uploadInputStreamChangeToImageToCos(InputStream is, String openId, String secretid, String secretkey, String wxaCodePath) {
        String url = "";

        String timeStamp = DateUtils.timeStamp();


        //1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretid, secretkey);

        //2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        //clientConfig中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者接口文档 FAQ 中说明。
        ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));


        //3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);

        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        String bucketName = "huicheduo-1253871561";
        // 指定要上传到 COS 上对象键
        String key = wxaCodePath + timeStamp + openId + ".png";

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, is, new ObjectMetadata());



            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

            url = "https://" + bucketName + ".cos-website.ap-shanghai.myqcloud.com/" + key;

            cosClient.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CosUtils",e);
        } finally {
//              cos            在浏览器上无法预览，只是进行下载
//              cos-website    解决浏览器上无法预览的问题
//            url = "https://" + bucketName + ".cos-website.ap-shanghai.myqcloud.com/" + key;
            logger.info("url>>"+url);
        }
        return url;
    }


}
